package com.okilo.online.app.act

import android.Manifest
import android.content.Intent
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.okilo.online.app.OkiloApplication
import com.okilo.online.app.base.app.OkiloActStackManager
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.databinding.OkiloActLaunchBinding
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.tools.OkiloTitleBarUtil
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.helper.OkiloAnalysisHp
import com.okilo.online.app.tools.helper.OkiloConfigCustomerHp
import com.okilo.online.app.tools.helper.OkiloUpdateHp
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import com.okilo.online.app.dialog.OkiloUpdateDlog
import com.okilo.online.app.pet.OkiloConfigsPet
import com.okilo.online.app.pet.OkiloTimeZonePet
import com.okilo.online.app.pet.view.IOkiloConfigs
import com.okilo.online.app.pet.view.IOkiloTimeZone
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/12/5 20:18
 * @Annotation：
 */
class OkiloLaunchAct: OkiloComAct(), IOkiloTimeZone, IOkiloConfigs.IOkiloConfigCustomer,
    EasyPermissions.RationaleCallbacks {
    lateinit var binding: OkiloActLaunchBinding

    //时区
    private var timeZomePet: OkiloTimeZonePet? = null
    //配置
    private var configsPet: OkiloConfigsPet? = null

    private val PERMISSION_REQUEST_CODE : Int = 10001;
    //是否需要去登录， 只有时区接口的 时区转发字段发生变化时，需要改变此值
    private var isToLogin = false

    private var okiloLaunchUpdateHp: OkiloUpdateHp? = null
    private val okiloLaunchUpdateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // TODO: 更新成功，进入主界面
                pushOkiloLaunchIntentPage()
            } else {
                // 1、用户取消或失败，不处理，继续进入主界面
                // 2、如果需要强制，建议跳转应用商店，拦截进入主界面
                if (okiloLaunchUpdateHp == null) {
                    pushOkiloLaunchIntentPage()
                    return@registerForActivityResult
                }
                okiloLaunchUpdateHp?.handleNoUpdate {
                    pushOkiloLaunchIntentPage()
                }
            }
        }

    override val pageName: String = "Launch_Page"

    override fun createOkiloContentView(): View? {
        binding = OkiloActLaunchBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeOkiloViews() {
        OkiloTitleBarUtil.setStatusBarLightMode(this, false)
        setBackExit(true)
        //关闭所有页面
        OkiloActStackManager.finishAllActivity(OkiloLaunchAct::class.java)
        //启动需要重置审核中、放款中显示的公告提示次数
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_DIALOG_NOTICE_NUM,0)
    }

    override fun setupOkiloEventListeners() {
        binding.okiloLaunchAppName.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showOkiloLoading()
                timeZomePet?.gOkiloTimeZoneRequest()
            }
        })
    }

    override fun loadOkiloData() {
        if (timeZomePet == null){
            timeZomePet = OkiloTimeZonePet(this)
        }
        if (configsPet == null){
            configsPet = OkiloConfigsPet(this)
        }

        showOkiloLoading()
        timeZomePet?.gOkiloTimeZoneRequest()
    }

    /**
     * 时区转发成功
     */
    override fun sOkiloTimeZoneCallback(timeZone: String) {
        //获取上次保存的时区转发，仅用于改变已登录状态下，是否需要重新登录判断
        val saveTimeZone = OkiloSharedHp.gOkiloSharedString(OkiloSharedKey.SP_OKILO_TIMEZONE)
        if (saveTimeZone != timeZone){
            isToLogin = true
        }

        //获取客服配置
        configsPet?.gOkiloConfigCustomerRequest(this)
    }

    /**
     * 客服配置获取成功
     */
    override fun sOkiloConfigCustomerCallback() {
        //是否强制更新版本
        val isUpdate = OkiloConfigCustomerHp.iOkiloReleaseMustUpdate()
        if (isUpdate){
            sOkiloLaunchUpdateDialog()
            return
        }
        pushOkiloLaunchIntentPage()
    }

    /**
     * 执行跳转逻辑
     */
    fun pushOkiloLaunchIntentPage(){
        //权限页操作状态 : 0未操作  1已同意  -1拒绝
        val permissionStatus = OkiloSharedHp.gOkiloSharedInt(OkiloSharedKey.SP_OKILO_PERMISSIONS_STATUS)
        //权限列表未操作 -> 进入权限列表
        if (permissionStatus == 0){
            pushOkiloPermPage()
            return
        }

        //已登录 - 进入主页
        if (OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_LOGIN)){
            pushOkiloMainPage()
            return
        }
        //进入登录页面
        pushOkiloLoginPage()
    }

    /**
     * 进入登录页
     */
    private fun pushOkiloLoginPage() {
        onIntent(OkiloUserLoginAct::class.java)
        finish()
    }

    /**
     * 进入主页
     */
    private fun pushOkiloMainPage() {
        //时区转发发生变化 需要重新登录
        if (isToLogin){
            pushOkiloLoginPage()
            return
        }
        //初始化analysis lib 赋值 用户id 和 token
        OkiloAnalysisHp.initLibAtLoginSuccess(OkiloApplication.Companion.app)
        onIntent(OkiloMainAct::class.java)
        finish()
    }

    /**
     * 进入权限申明列表
     */
    private fun pushOkiloPermPage(){
        val intent = Intent(this, OkiloPermAct::class.java)
        permissionResultLauncher.launch(intent)
    }

    /**
     * 版本更新Dialog
     */
    private fun sOkiloLaunchUpdateDialog(){
        val updateDialog =
            OkiloUpdateDlog(this, pageName, object : OkiloUpdateDlog.IDialogCallback {
                override fun onUpdateClick() {
                    try {
                        if (okiloLaunchUpdateHp == null) {
                            okiloLaunchUpdateHp = OkiloUpdateHp(
                                activity = this@OkiloLaunchAct,
                                forceUpdate = true,
                                okiloLaunchUpdateLauncher
                            )
                        }
                        okiloLaunchUpdateHp?.checkAndStartUpdate { pushOkiloLaunchIntentPage() }
                    } catch (e: Exception) {
                        pushOkiloLaunchIntentPage()
                    }
                }
            })
        updateDialog.show()
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        OkiloLog.i("Permission page onPermissionsGranted, code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE){
            addEventPointRequestAction(
                OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_SYSTEM_AGREE,
                Manifest.permission.READ_SMS)
            pushOkiloPermPage()
        }
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        OkiloLog.i("onPermissionsDenied code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE){
            addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_SYSTEM_DENY, Manifest.permission.READ_SMS)
            OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_PERMISSIONS_STATUS,-1)
            pushOkiloPermPage()
        }
    }

    override fun onRationaleAccepted(requestCode: Int) {
        OkiloLog.i("onRationaleAccepted, code: $requestCode")
    }

    override fun onRationaleDenied(requestCode: Int) {
        OkiloLog.i("onRationaleDenied, code: $requestCode")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE){
            // 判断权限是否申请成功
            val hasPermissions = EasyPermissions.hasPermissions(this, Manifest.permission.READ_SMS)
            if (hasPermissions){
                addEventPointRequestAction(
                    OkiloEventPointType.OKILO_CLICK_TRACK.PERMISSION_SYSTEM_AGREE,
                    Manifest.permission.READ_SMS)
                pushOkiloPermPage()
            }
        }
    }

    /**
     * 权限申请结果
     */
    private val permissionResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                //已登录 - 进入主页
                if (OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_LOGIN)){
                    pushOkiloMainPage()
                    return@registerForActivityResult
                }
                //进入登录页面
                pushOkiloLoginPage()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            okiloLaunchUpdateHp?.resumeIfInProgress()
        } catch (e: Exception) {
            //
        }
    }
}